﻿Public Class xtf_LISTADOINFORMEPedido_
    Public WithEvents dtt_DataTable As New DataTable
    Public PERMISOImprimir As String = ""


#Region "Total registros ..."

    Private Sub gdv_general_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        Dim Total As Decimal
        For Each row As DataRow In dtt_DataTable.Rows
            Total += row("importe")
        Next
        bsi_registros.Caption = "Total documentos Listadas: " & gdv_general.RowCount & "  Importe Total: " & Math.Round(Total, int_cantdecimales)
    End Sub

#End Region

#Region "General"
    Private Sub bbi_cerrar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_cerrar.ItemClick
        Me.Close()
    End Sub

    Private Sub btn_Cerrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Cerrar.Click
        Me.Close()
    End Sub

    Private Sub bbi_actualizar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_actualizar.ItemClick
        dtt_DataTable = New DataTable
        IniciarLista()
    End Sub

    Private Sub xtf_Listado_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        guardar_config_usuariocolumna_()
    End Sub

    Private Sub guardar_config_usuariocolumna_()
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(UsuarioLOG.idusuario, Me.Name) Then
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.Modificar()
        Else
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.idusuario = UsuarioLOG.idusuario
            obj_config_usuariocolumna_.modulo = Me.Name
            obj_config_usuariocolumna_.Nuevo()
        End If
    End Sub

    Public Sub FiltrarColumnas()
        Dim int_IDUsuario As Integer = UsuarioLOG.idusuario
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        gdv_general.BeginUpdate()
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(int_IDUsuario, Me.Name) Then
            SetLayoutData(gdv_general, obj_config_usuariocolumna_.xml)
        End If

        PerzonalizarControl(gdc_general)

        gdv_general.EndUpdate()
    End Sub

    Private Function GetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView) As Byte()
        Dim stream As New System.IO.MemoryStream()
        prm_GridView.SaveLayoutToStream(stream)
        Return stream.GetBuffer()
    End Function

    Private Sub SetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView, ByVal data As Byte())
        If data Is Nothing OrElse data.Length = 0 Then
            Return
        End If
        Dim stream As New System.IO.MemoryStream(data)
        Try
            prm_GridView.RestoreLayoutFromStream(stream)
        Catch ex As Exception
            Throw New Exception("Wrong data format", ex)
        End Try
    End Sub

    Private Sub bbi_columnas_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_columnas.ItemClick
        gdv_general.ColumnsCustomization()
    End Sub
#End Region

    Public Sub New()

        Me.Cursor = Cursors.WaitCursor
        InitializeComponent()
        PERMISOImprimir = "002002005"
        lbl_modulo.Text = "Resumen diario de Reparto"
        Me.Text = lbl_modulo.Text : lbl_modulodescripcion.Text = "Listado de " & lbl_modulo.Text & "."
        IniciarLista()
        Me.Cursor = Cursors.Default

        dtp_fechaDesde.DateTime = Now

        Dim desde As DateTime = Now
        Dim hasta As DateTime = Now
        dtp_fechaDesde.DateTime = desde
        dtp_fechaHasta.DateTime = hasta

        Dim transporte_ As New cls_transporte_
        transporte_.CargarTodos()
        If IsNothing(transporte_.Items) Then
            transporte_.Items = New Collections.Generic.List(Of cls_transporte_)
        End If
        Dim transporteTODOS As New cls_transporte_
        transporteTODOS.tercero = New cls_tercero_
        transporteTODOS.tercero.nombres = "TODOS"
        transporte_.Items.Add(transporteTODOS)

        cargarCombo(cbo_transporte, transporte_.Items)
        cbo_transporte.Enabled = True
        cbo_transporte.EditValue = 0

    End Sub

    Public Sub IniciarLista()
        Try
            gdc_general.BeginUpdate()
            dtt_DataTable = New DataTable

            gdc_general.DataSource = dtt_DataTable
            'ulg_Lista.DisplayLayout.GroupByBox.Style = Infragistics.Win.UltraWinGrid.GroupByBoxStyle.Full

            dtt_DataTable.Columns.Add("Identificador(ID)")
            dtt_DataTable.Columns.Add("Razón Social")
            dtt_DataTable.Columns.Add("Nombre de Fantasía")
            dtt_DataTable.Columns.Add("Nro. Pedido")
            dtt_DataTable.Columns.Add("Fecha")
            dtt_DataTable.Columns.Add("Importe", GetType(Decimal))
            dtt_DataTable.Columns.Add("Transportista")
            dtt_DataTable.Columns.Add("Pagado", GetType(Decimal))
            dtt_DataTable.Columns.Add("Pagado Total", GetType(Boolean))

            'Dim obj_Personal_ As New cls_personal_
            'If obj_Personal_.CargarTodos() Then
            '    For Each Personal As cls_personal_ In obj_Personal_.Items
            '        AgregarItem(Personal)
            '    Next
            'End If
            gdv_general.PopulateColumns()
            gdv_general.Columns("Importe").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            gdv_general.Columns("Importe").AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            gdv_general.Columns("Pagado").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            gdv_general.Columns("Pagado").AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far

            gdv_general.Columns("Razón Social").OptionsColumn.AllowEdit = False
            gdv_general.Columns("Nombre de Fantasía").OptionsColumn.AllowEdit = False
            gdv_general.Columns("Nro. Pedido").OptionsColumn.AllowEdit = False
            gdv_general.Columns("Importe").OptionsColumn.AllowEdit = False
            gdv_general.Columns("Transportista").OptionsColumn.AllowEdit = False
            gdv_general.Columns("Identificador(ID)").OptionsColumn.AllowEdit = False
            gdv_general.Columns("Fecha").OptionsColumn.AllowEdit = False

            gdv_general.Columns("Pagado").ColumnEdit = New DevExpress.XtraEditors.Repository.RepositoryItemTextEdit
            CType(gdv_general.Columns("Pagado").ColumnEdit, DevExpress.XtraEditors.Repository.RepositoryItemTextEdit).Mask.MaskType = DevExpress.XtraEditors.Mask.MaskType.Numeric
            CType(gdv_general.Columns("Pagado").ColumnEdit, DevExpress.XtraEditors.Repository.RepositoryItemTextEdit).Mask.EditMask = "n" & int_cantdecimales
            CType(gdv_general.Columns("Pagado").ColumnEdit, DevExpress.XtraEditors.Repository.RepositoryItemTextEdit).Mask.UseMaskAsDisplayFormat = True
            AddHandler CType(gdv_general.Columns("Pagado").ColumnEdit, DevExpress.XtraEditors.Repository.RepositoryItemTextEdit).Click, AddressOf RepositoryItemTextEdit_Click

            gdv_general.Columns("Pagado Total").ColumnEdit = New DevExpress.XtraEditors.Repository.RepositoryItemCheckEdit

            FiltrarColumnas()
            gdv_general.BestFitColumns()
            gdc_general.EndUpdate()
            btn_buscar_Click(Nothing, Nothing)
        Catch ex As Exception
            'Dim frmError As New frm_ErrorManager(ex.Message)
        End Try
    End Sub

    Public Sub RepositoryItemTextEdit_Click(ByVal sender As Object, ByVal e As EventArgs)
        CType(sender, DevExpress.XtraEditors.TextEdit).SelectAll()
    End Sub

    Public Sub AgregarItem(ByRef documento As cls_documento_)
        Dim Row As DataRow = dtt_DataTable.NewRow
        Row("Identificador(ID)") = documento.iddocumento
        Dim cliente As New cls_cliente_
        If cliente.BuscarXidtercero(documento.tercero.idtercero) Then
            Row("Nombre de Fantasía") = cliente.nombrefantasia
            Row("Razón Social") = cliente.razonsocial
        End If
        Row("Fecha") = documento.fecha.ToShortDateString
        Row("Nro. Pedido") = Format(documento.numero, "0000000000")
        Dim t As Decimal
        documento.Totales(1, 1, 1, 1, t)
        Row("Importe") = t
        If Not IsNothing(documento.transporte) Then
            Row("Transportista") = documento.transporte.ToString
        End If
        If Not IsNothing(documento.cajaasiento) Then
            Row("Pagado") = documento.cajaasiento.importe
            If Row("Pagado") >= Row("Importe") Then
                Row("Pagado Total") = True
            Else
                Row("Pagado Total") = False
            End If
        Else
            Row("Pagado") = 0
            Row("Pagado Total") = False
        End If

        dtt_DataTable.Rows.Add(Row)
        'ulg_Lista.Rows(ulg_Lista.Rows.Count - 1) = Persona.Height = 19
    End Sub

    Public Sub btn_buscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_buscar.Click
        dtt_DataTable.Rows.Clear()
        Dim obj_documento_ As New cls_documento_
        Dim desde As DateTime = New Date(dtp_fechaDesde.DateTime.Year, dtp_fechaDesde.DateTime.Month, dtp_fechaDesde.DateTime.Day, 0, 0, 0)
        Dim hasta As DateTime = New Date(dtp_fechaHasta.DateTime.Year, dtp_fechaHasta.DateTime.Month, dtp_fechaHasta.DateTime.Day, 23, 59, 59)
        If cbo_transporte.EditValue = 0 Then
            If obj_documento_.CargarXfechaXtipodocumento(desde, hasta, cls_documento_.enu_tipodocumento.PedidoCliente) Then
                For Each documento As cls_documento_ In obj_documento_.Items
                    AgregarItem(documento)
                Next
            End If
        Else
            If obj_documento_.CargarXfechaXtipodocumentoXidtransporte(desde, hasta, cls_documento_.enu_tipodocumento.PedidoCliente, cbo_transporte.EditValue) Then
                For Each documento As cls_documento_ In obj_documento_.Items
                    AgregarItem(documento)
                Next
            End If
        End If

    End Sub

    Public Sub bbi_imprimir_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_imprimir.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            ShowGridPreview(lbl_modulo.Text, gdc_general, False)
        End If
    End Sub

    Public Sub bbi_exportarPDF_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarPDF.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            ExportGrid(lbl_modulo.Text, gdc_general, "PDF")
        End If
    End Sub

    Public Sub bbi_vistaprevia_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_vistaprevia.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            ShowGridPreview(lbl_modulo.Text, gdc_general, True)
        End If
    End Sub

    Public Sub bbi_exportarExcel_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarExcel.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            ExportGrid(lbl_modulo.Text, gdc_general, "XLS")
        End If
    End Sub

    Private Sub gdv_listaprecioarticulo__CellValueChanged(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gdv_general.CellValueChanged
        Select Case e.Column.FieldName
            Case "Pagado"
                Dim row As DataRow = gdv_general.GetDataRow(e.RowHandle)
                Dim documento As New cls_documento_
                documento.Buscar(row("Identificador(ID)"))

                If Not IsNothing(documento.cajaasiento) Then
                    'documento.cajaasiento.importe = row("Pagado")
                    'documento.cajaasiento.Modificar()
                    If row("Pagado") = 0 Then
                        documento.cajaasiento.Eliminar(documento.cajaasiento.idcajaasiento)
                    Else
                        documento.cajaasiento.importe = row("Pagado")
                        documento.cajaasiento.Modificar()
                    End If
                Else
                    Dim caja As New cls_caja_
                    If Not caja.BuscarXfechaXtipo(documento.fecha, cls_caja_.enu_tipo.Reparto) Then
                        caja.fecha = documento.fecha
                        caja.tipo = cls_caja_.enu_tipo.Reparto
                        caja.Nuevo(True)
                    End If

                    Dim cajaasiento As New cls_cajaasiento_
                    cajaasiento.idcaja = caja.idcaja
                    cajaasiento.idtercero = documento.idtercero
                    cajaasiento.importe = row("Pagado")
                    cajaasiento.tipoimporte = cls_cajaasiento_.enu_tipoimporte.Ingreso
                    cajaasiento.tipo = cls_cajaasiento_.enu_tipo.Automatico
                    cajaasiento.fecha = documento.fecha
                    cajaasiento.iddocumento = documento.iddocumento
                    cajaasiento.observaciones = Format(documento.numero, "0000000000")
                    Dim parametroConcepto As New cls_config_parametro_
                    parametroConcepto.Buscar("cajaasientoConceptoPedido")
                    cajaasiento.idcajaconcepto = parametroConcepto.valor
                    cajaasiento.Nuevo()
                End If
        End Select
    End Sub

    Private Sub btn_exportarImprimir_Click(sender As System.Object, e As System.EventArgs) Handles btn_exportarImprimir.Click
        bbi_vistaprevia_ItemClick(Nothing, Nothing)
    End Sub

    Private Sub gdv_general_CellValueChanging(sender As Object, e As DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs) Handles gdv_general.CellValueChanging
        Select Case e.Column.FieldName
            Case "Pagado Total"
                Dim row As DataRow = gdv_general.GetDataRow(e.RowHandle)
                If e.Value = True Then
                    row("Pagado") = row("Importe")
                Else
                    row("Pagado") = 0
                End If
                Dim documento As New cls_documento_
                documento.Buscar(row("Identificador(ID)"))

                If Not IsNothing(documento.cajaasiento) Then
                    If row("Pagado") = 0 Then
                        documento.cajaasiento.Eliminar(documento.cajaasiento.idcajaasiento)
                    Else
                        documento.cajaasiento.importe = row("Pagado")
                        documento.cajaasiento.Modificar()
                    End If
                Else
                    Dim caja As New cls_caja_
                    If Not caja.BuscarXfechaXtipo(documento.fecha, cls_caja_.enu_tipo.Reparto) Then
                        caja.fecha = documento.fecha
                        caja.tipo = cls_caja_.enu_tipo.Reparto
                        caja.Nuevo(True)
                    End If

                    Dim cajaasiento As New cls_cajaasiento_
                    cajaasiento.idcaja = caja.idcaja
                    cajaasiento.idtercero = documento.idtercero
                    cajaasiento.importe = row("Pagado")
                    cajaasiento.tipoimporte = cls_cajaasiento_.enu_tipoimporte.Ingreso
                    cajaasiento.tipo = cls_cajaasiento_.enu_tipo.Automatico
                    cajaasiento.fecha = documento.fecha
                    cajaasiento.iddocumento = documento.iddocumento
                    cajaasiento.observaciones = Format(documento.numero, "0000000000")
                    Dim parametroConcepto As New cls_config_parametro_
                    parametroConcepto.Buscar("cajaasientoConceptoPedido")
                    cajaasiento.idcajaconcepto = parametroConcepto.valor
                    cajaasiento.Nuevo()
                End If
        End Select
    End Sub
End Class